package com.runvp.common.util.enc;

import com.runvp.common.hex.HexConvert;

import javax.crypto.Cipher;
import javax.crypto.spec.GCMParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;

public class AESGCMDecryption12 {
    public static void main(String[] args) throws Exception {
        // 16进制字符串转换为字节数组
        byte[] ivBytes = hexStringToByteArray(HexConvert.str2HexStr("98BPRR4Wve41"));
        byte[] keyBytes = hexStringToByteArray(HexConvert.str2HexStr("BMrcujdO0XDjvOOa"));
        byte[] tagBytes = hexStringToByteArray("7130C4C92F60B7EB4D565B1DDFC2559E");
        byte[] encryptedBytes = hexStringToByteArray("6BE3153AFC79025ACDF03CB38D988927BBF1DB4FCE387729CB19AB13FEC136");

        // 初始化Cipher对象
        Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding");

        // 设置Key和IV
        SecretKeySpec keySpec = new SecretKeySpec(keyBytes, "AES");
        GCMParameterSpec gcmParameterSpec = new GCMParameterSpec(128, ivBytes);
        cipher.init(Cipher.DECRYPT_MODE, keySpec, gcmParameterSpec);

        // 添加tag进行验证
        cipher.updateAAD(tagBytes);

        // 执行解密
        byte[] decryptedBytes = cipher.doFinal(encryptedBytes);

        // 解密后的数据
        String decryptedString = new String(decryptedBytes, StandardCharsets.UTF_8);
        System.out.println("解密后的数据: " + decryptedString);
    }

    private static byte[] hexStringToByteArray(String s) {
        int len = s.length();
        byte[] data = new byte[len / 2];
        for (int i = 0; i < len; i += 2) {
            data[i / 2] = (byte) ((Character.digit(s.charAt(i), 16) << 4)
                    + Character.digit(s.charAt(i+1), 16));
        }
        return data;
    }
}
